// pages/post/post_content/post_content.js
import Dialog from '../../../miniprogram_npm/@vant/weapp/dialog/dialog';
let util = require('../../../utils/content_check.js')
const { formatTime } = require('../../../utils/util.js')
const app = getApp()
Page({

  data: {
    articleid:null,
    authorid:null,
    createtime:null,
    title:null,
    content:null,
    theme:null,
    statusflag:null,
    deleteflag:null,
    communityid:null,
    nickName:null,
    avatar: null,

    userid:null,

    comments:[],

    input_focus:false,
    canDelete:false,
    canReply:true,

    //需要回复的评论id 如果是帖子本身为-1
    NCparentcommentid: -1,
    NCcontent: null,
    NCcommentedid: null,
    NCcreatetime: null,

    inputPlaceHolder:'快来发表评论吧 ~ ',


    show:false,
    radio:null,
    accuseForm:{
      type:null,
      memo:'',
      articleid:null,
      fromsource:1
    },
    
    isCollected:null,   //收藏与否

    pageSize:15,
    pageNum: 1,
    total: null,
  },

  // 判断由哪个页面跳转而来，从而决定返回哪个页面
  onLoad: function (options) {
    // let pages = getCurrentPages();
    // let prevpage = pages[pages.length - 2];
    var v = 'accuseForm.articleid'
    this.setData({
      articleid:options.articleid,
      [v]:options.articleid,
      userid: app.globalData.userInfo.userId
    })
    //获得文章详情
    app.sendGetRequest('/bbs/'+this.data.articleid,(res) => {
      res.content = res.content.replace(/\<img/gi, '<img style="max-width:100%;height:auto" ')
      
      this.setData({
        authorid:res.authorid,
        createtime:res.createtime,
        title:res.title,
        content:res.content,
        theme:res.theme,
        statusflag:res.statusflag,
        deleteflag:res.deleteflag,
        communityid:res.communityid,
        nickName:res.nickName,
        avatar: res.avatar,
        NCcommentedid:res.authorid,
      })
    })
    //获得文章评论
    // this.getComment()
    // 测试： 获得文章评论
    this.newGetComment();
    //获得文章收藏情况
    this.checkIsCollect()
    //看是否是
    if(this.data.userid == this.data.authorid){
      this.setData({
        isAuthor: true
      })
    }

  },
  getComment(){
    this.newGetComment()
  },
  checkIsCollect(){
    var that = this
    var data = {
      id:null,
      articleid :this.data.articleid,
      userid:null,
      communityid:null
    }
    console.log("__",data)
    app.sendPostRequest('/bbs/favorite/isFa',data,(res)=>{
      console.log("******",res)
      if(res==1){
        that.setData({
          isCollected:true
        })
      }else if(res==0){
        that.setData({
          isCollected:false
        })
      }else{
        console.log(res)
      }
      console.log("result",that.data.isCollected)
    },(err)=>{
      console.log(err)
    })
  },

  newGetComment(){
    var param = {
      pageSize: this.data.pageSize,
      pageNum: this.data.pageNum
    }
    app.sendGetRequestWithData('/bbs/getCommentList/'+this.data.articleid, param, (res) => {
      this.setData({
        comments:res.rows,
        total: res.total
      })
    })
    // app.sendGetRequest('/bbs/getCommentList/'+this.data.articleid,(res) => {
    //   this.setData({
    //     comments:res.rows
    //   })
    // })
  },
  //滚动加载更多评论
  scrollToLower: function(e){
    var nextPage = this.data.pageNum + 1;
    if(nextPage * this.data.pageSize - this.data.total > this.data.pageSize){
      return
    }
    var oldList = this.data.comments
    var param = {
      pageSize: this.data.pageSize,
      pageNum: this.data.pageNum + 1,
    }
    app.sendGetRequestWithData('/bbs/getCommentList/'+this.data.articleid, param,(res) => {
      var after = oldList.concat(res.rows)
      this.setData({
        comments: after,
        total: res.total,
        pageNum: nextPage
      })
    })
  },
  // 加载更多子评论
  loadMoreComment(e){
    var pageSize = e.currentTarget.dataset.pagesize;
    var index = e.currentTarget.dataset.index;
    var commentid = e.currentTarget.dataset.commentid;
    var pageNum = e.currentTarget.dataset.pagenum;
    var beforeComments = this.data.comments[index].replyComments
    if(pageNum == null){
      pageNum = 0;
      beforeComments = []
    }
    pageNum=pageNum+1
    var param = {
      pageSize: pageSize,
      pageNum: pageNum
    }
    var afterPageNum = 'comments['+index+'].pageNum'
    var afterReplyComments = 'comments['+index+'].replyComments'
    app.sendGetRequestWithData('/bbs/getAllChildComment/'+commentid, param, (res)=>{
      var moreComment = beforeComments.concat(res.rows)
      this.setData({
        [afterPageNum]: pageNum,
        [afterReplyComments]: moreComment
      })
    })
    console.log(this.data.comments)
  },

  // 收藏
  collectAdd: function (e) {
    var that = this
    var data = {
      articleid:this.data.articleid
    }
    app.sendPostRequest('/bbs/favorite',data,(res)=>{
      if(res.code==200){
        wx.showToast({
          title: '收藏成功',
        
        })
        that.changeCollect()
      }else if(res.code==300){
        wx.showToast({
          title: '已经收藏',
          icon:'none'
        })
      }else{
        console.log(res)
      }
    },(err)=>{
      console.log(err)
    })
  },
  changeCollect(){
    this.setData({
      isCollected:!this.data.isCollected
    })
  },
  //取消收藏
  collectRemote:function(e){
    var that = this
    var data = {
      articleid:this.data.articleid
    }
    app.sendPostRequest('/bbs/favorite/remote',data,(res)=>{
      if(res.code==200){
        wx.showToast({
          title: '取消收藏成功',
        
        })
        that.changeCollect()
      }else if(res.code==300){
        wx.showToast({
          title: '已经取消收藏',
          icon:'none'
        })
      }else{
        console.log(res)
      }
    },(err)=>{
      console.log(err)
    })
  },
  //点击“举报”按钮弹窗
  jubao: function(e){
    this.setData({
      show:true
    })
    console.log(this.data.show)
  },

  edit_post: function (e){
    wx.navigateTo({
      url: '../edit_post/edit_post?post_id=' + this.data.articleid,
    })
  },

  // 评论输入框接收输入
  onInputComment: function (e) {
    var comment = e.detail.value;
    this.setData({
      NCcomment: comment
    })
  },
  resetNewComment:function(){
  
    this.setData({
      NCparentcommentid :-1,
      NCcontent :null,
      NCcommentedid :null,
      NCcreatetime :null,
      inputPlaceHolder:'快来发表评论吧 ~ '
    })
  },
  // createComment: function (comment){
  //   var index = this.data.comments.length;
  //   // 插入缓存
  //   var viewer_info = wx.getStorageSync('user_info')
  //   var time = []
  //   var myDate = new Date()
  //   time.push(myDate.getFullYear(), myDate.getMonth(), myDate.getDate(), myDate.getHours(), myDate.getMinutes(), myDate.getSeconds())
  //   var comment_item = {
  //     index: index,
  //     user_id: viewer_info.user_id,
  //     user_name: viewer_info.user_nickname,
  //     user_pic: viewer_info.user_pic,
  //     comment: comment,
  //     time: time,
  //     toReply: this.data.reply
  //   };
  //   this.data.post.comment_list.push(comment_item)
  //   this.update_post_to_storage()

  //   // 更新页面数据
  //   this.update_page()
  // },
  // 评论信息（内容，评论人）插入缓存中该帖子对应的评论列表里
  onSendTap: function(e){
    
    
    var time = formatTime(new Date())
    console.log("time",time)
    this.setData({
      NCcreatetime : time
    })
    var newCo = {
      createtime :this.data.NCcreatetime,
      articleid:this.data.articleid,
      content :this.data.NCcontent,
      commentedid:this.data.NCcommentedid,
      parentcommentid:this.data.NCparentcommentid
      
    }
    var that = this
    app.sendPostRequest('/bbs/commentInsert/',newCo,(res) => {
      if(res.code == 200){
        wx.showToast({
          title: '评论成功!',
          icon: 'success',
          duration: 2000
        })
        // wx.redirectTo({
        //   url: '../post_content/post_content?articleid=' + that.data.articleid,
        // })
        this.getComment()
        this.resetNewComment()
      }})

  },

  tap_comment: function (e){
    var that = this
    console.log(e)
    var commentid = e.currentTarget.dataset.commentid
    var commenterid = e.currentTarget.dataset.commenterid
    var parentcommentid = e.currentTarget.dataset.parentcommentid
    // var canReply = e.currentTarget.dataset.cp
    var canReply = true
    var canDelete = this.data.isAuthor || ( this.data.userid == commenterid ? true : false )
    var nickname = e.currentTarget.dataset.thisname
    var function_list = []
    console.log("commentid",commentid)
    console.log("nickname",nickname)
    if(canReply||canDelete){
      // if(canReply){
      //   function_list.push('回复')
      // }
      function_list.push('回复')
      if(canDelete){
        function_list.push('删除')
      }
      wx.showActionSheet({
        itemList: function_list,
        success: function(res) {
            // console.log(res.tapIndex)
            var option = function_list[res.tapIndex]
            // console.log(category)
            if(option == '删除'){
              var data = {
                commentid: commentid,
                deleteflag: 1
              }
              app.sendPutRequest('/bbs/commentUpdateDelete', data, (res)=>{
                console.log(res)
              },(err)=>{console.log(err)})
              // 更新页面数据
              that.getComment()
            }else if(option == '回复'){
              that.setData({
                input_focus: true,
                NCcommentedid:commenterid,
                inputPlaceHolder:'回复 '+nickname,
              })
              if(commentid!=-1){
                that.setData({
                  NCparentcommentid: parentcommentid
                })
              }else{
                that.setData({
                  NCparentcommentid: -1
                })
              }
            }
        },
        fail: function(res) {
            console.log(res.errMsg)
        }
      })
    }
    
  },

  // 把评论整理成正确的显示顺序
  get_comments_sorted: function (list){
    // index从小到大 等同于 时间先后，不需要再排序了
    // 首先选出不是回复某人的单独评论，按时间从先到后排序，再把回复某条的评论插到对应评论组里

    // [[0,1], [2], [3]]只存储评论的index
    var comment_group_list = []
    // 存储回复类评论的整个评论信息
    var comment_to_reply_list = []

    for(var i=0; i<list.length; i++){
      if(list[i].toReply==null){
        comment_group_list.push([list[i].index])
      }else{
        comment_to_reply_list.push(list[i])
      }
    }
    for(var i=0; i<comment_to_reply_list.length; i++){
      for(var j=0; j<comment_group_list.length; j++){
        if(this.inList(comment_to_reply_list[i].toReply, comment_group_list[j])){
          comment_group_list[j].push(comment_to_reply_list[i].index)
          break;
        }
      }
    }
    var sorted_comment_index_list = [].concat.apply([], comment_group_list)
    var result = []
    for(var i=0; i<sorted_comment_index_list.length; i++){
      for(var j=0; j<list.length; j++){
        if(list[j].index == sorted_comment_index_list[i]){
          result.push(list[j])
        }
      }
    }
    return result
  },

  inList: function (item, list){
    var result = false
    for(var i=0; i<list.length; i++){
      if(item==list[i]){
        result = true
        break
      }
    }
    return result
  },
  radioCellonChange(e){
    console.log(e)
  },
  //举报表单中类型的绑定
  onClick(e){
    var target = e.target.dataset.name
    var v = 'accuseForm.type'
    this.setData({
      [v]:target
    })
    console.log(this.data.accuseForm)
  },
  //举报表单的文字输入绑定
  accuseFormInputChange(e){
    var v = 'accuseForm.memo'
    this.setData({
      [v]:e.detail
    })
    console.log(this.data.accuseForm)
  },
  //提交举报表单
  submitAccuse(){
    var that = this
    if(this.data.accuseForm.type==null){
      wx.showToast({
        title: '举报类型为必选项',
        icon:'error'
      })
      return;
    }
    app.sendPostRequest('/system/report',this.data.accuseForm,(res)=>{
      if(res.code==300){
        wx.showToast({
          title: '您已举报过该帖子',
          icon:'error'
        })
      }else{
        wx.showToast({
          title: '举报成功',
          icon:'success'
        })
      }
      that.setData({
        show:false
      })
    },(err)=>{
      console.log(err)
    })
  }

})